package com.yy.finvideoplayer

import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import com.yy.finvideoplayer.model.QSVideo

/**
 * @Description: VideoPopWindow
 * @Author: yiw89
 * @CreateDate: 2025/9/1 17:08
 * @Version: 1.0
 */
class VideoPopWindow(context: Context, qsVideos: List<QSVideo>, index: Int) :
    PopupWindow(), View.OnClickListener {
    var h: Int

    fun showTop(view: View) {
        showAsDropDown(view, 0, -h - view.measuredHeight)
    }

    override fun onClick(v: View) {
        itemListener!!.onClick(v.id)
        dismiss()
    }

    private var itemListener: OnItemListener? = null

    init {
        val popview = LayoutInflater.from(context).inflate(
            R.layout.pop_definition, FrameLayout(context), false
        ) as ViewGroup
        val density = context.resources.displayMetrics.density
        val padding = (density * 12).toInt()
        for (i in qsVideos.indices) {
            val qsVideo: QSVideo = qsVideos[i]
            val textView = TextView(context)
            textView.id = i
            textView.setPadding(padding, padding / 2, padding, padding / 2)
            textView.setText(qsVideo.resolution())
            textView.textSize = 14f
            textView.setOnClickListener(this)
            textView.setTextColor(if (index == i) context.resources.getColor(R.color.colorMain) else -0x1)
            popview.addView(textView)
        }
        val mode = View.MeasureSpec.AT_MOST
        //手动调用计算宽高
        popview.measure(
            View.MeasureSpec.makeMeasureSpec(1080, mode),
            View.MeasureSpec.makeMeasureSpec(1920, mode)
        )
        h = popview.measuredHeight
        //设置视图
        contentView = popview
        width = LinearLayout.LayoutParams.WRAP_CONTENT //设置宽
        height = LinearLayout.LayoutParams.WRAP_CONTENT //设置高
        isFocusable = true
        isOutsideTouchable = true
        // 刷新状态
        update()
        // 实例化一个ColorDrawable颜色为半透明
        val dw = ColorDrawable(0)
        // 点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener ，设置其他控件变化等操作
        setBackgroundDrawable(dw)
    }

    fun setOnItemListener(itemListener: OnItemListener) {
        this.itemListener = itemListener
    }


    interface OnItemListener {
        fun onClick(position: Int)
    }
}